package com.tnl.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;

import com.alibaba.fastjson.JSONObject;
  
/**
 * 加密
 * @author adela
 *
 */

public class WXBizDataCrypt {  
    private static WXBizDataCrypt instance = null;  
  
    private WXBizDataCrypt() {  
  
    }  
  
    public static WXBizDataCrypt getInstance() {  
        if (instance == null)  
            instance = new WXBizDataCrypt();  
        return instance;  
    }  

    public  String decrypt(String encryptedData, String sessionKey, String iv, String encodingFormat) throws Exception {  
        try {
        	System.out.println("encrydata="+encryptedData+"sesskey="+sessionKey+"   iv="+iv);
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");  
            BASE64Decoder base64Decoder = new BASE64Decoder();  
            byte[] _encryptedData = base64Decoder.decodeBuffer(encryptedData);  
            byte[] _sessionKey = base64Decoder.decodeBuffer(sessionKey);  
            byte[] _iv = base64Decoder.decodeBuffer(iv);  
            SecretKeySpec secretKeySpec = new SecretKeySpec(_sessionKey, "AES");  
            IvParameterSpec ivParameterSpec = new IvParameterSpec(_iv);  
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);  
            byte[] original = cipher.doFinal(_encryptedData);  
            byte[] bytes = PKCS7Encoder.decode(original);  
            String originalString = new String(bytes, "UTF-8");  
            return originalString;  
        } catch (Exception ex) {  
            return null;  
        }  
    }  
  
    public static void main(String[] args) throws Exception {  

        String sessionKey ="eQhTlf+Rpsqrp5jQHcqdTA==";
 
        String encryptedData ="r2SQtSqjTWc+gHhMlrX/r/lsofvGTliDJaRs2qjDavOEMxpqlolJ8aw0ru68YT21Wjz9+77aBcaec6PAjskoJYlw6+7nhNtf/amEInp15ejG2Xci9j3Z0FOXh3aIwYnefn5DYH14U7xfJfDmGS7yGMyh9kcnW/cHnnQiPR1VH0h3211HVyNQKgOyh5emeYWt8nt2bJZ+YkEX+l/yI0+o/w==";
        
        String iv = "VVjiQgHMvV2fsTgVD6ezfw=="; 
        
        String deString = WXBizDataCrypt.getInstance().decrypt(encryptedData, sessionKey, iv, "utf-8");  
        System.out.println(deString);  
        JSONObject jsonObject = JSONObject.parseObject(deString);  
        System.out.println(jsonObject);  
    	
    	
    }  
}  
